#include "user_global.h"
#include "modbus.h"
#include "user_device.h"

uchar Read_bit(uchar *bits,ushort addr, uchar n)
{
    uchar v;
    uchar m = addr & 7;     // addr % 8
    addr >>= 3;             // addr / 8

    v = bits[addr] >> m;

    if (n + m > 8)
        v |= bits[addr+1] << (8 - m);

    return v & ((1 << n) - 1);
}


uchar Read_RW_bit(ushort addr, uchar n)
{
    uchar v;
    uchar m = addr & 7;     // addr % 8
    addr >>= 3;             // addr / 8

    v = RW_BIT_FIRST[addr] >> m;

    if (n + m > 8)
        v |= RW_BIT_FIRST[addr+1] << (8 - m);

    return v & ((1 << n) - 1);
}

uchar Read_RO_bit(ushort addr, uchar n)
{
    uchar v;
    uchar m = addr & 7;     // addr % 8
    addr >>= 3;             // addr / 8

    v = RO_BIT_FIRST[addr] >> m;

    if (n + m > 8)
        v |= RO_BIT_FIRST[addr+1] << (8 - m);

    return v & ((1 << n) - 1);
}

// 从bits的addr开始写n位, 值为val对应的位. n不超过8
void write_bits(uchar *bits, ushort addr, uchar val, uchar n)
{
    uchar mask = (1 << n) - 1;
    uchar m = addr & 7; // addr % 8
    addr >>= 3;         // addr / 8

    // 将不使用的位清零
    val &= mask;

    bits[addr] &= ~(mask << m);
    bits[addr] |= val << m;

    if (n + m > 8)
    {
        bits[addr+1] &= ~(mask >> (8 - m));
        bits[addr+1] |= val  >> (8 - m);
    }

     // 条码扫描状态
    if (addr == 0 && m == 0)
        Scan_Code(rw_bit.start_scan);
    if (addr == 0 && m == 2)
        modbus_key_trigger[0] = 1;
    if (addr == 0 && m == 3)
        modbus_key_trigger[1] = 1;
}

void Write_RO_bit(ushort addr, uchar val, uchar n)
{
    write_bits(RO_BIT_FIRST, addr, val, n);
}

void Write_bit(ushort addr, uchar val, uchar n)
{
    write_bits(RW_BIT_FIRST, addr, val, n);
}

uchar Test_Bit(uchar *bits, ushort addr)
{
    return Read_bit(bits,addr,1);
}

void Set_Bit(uchar *bits, ushort addr, bit val)
{
    write_bits(bits, addr, val, 1);
}

void Set_RO_Bit(ushort addr)
{
    Write_RO_bit(addr, 1, 1);
}

void Reset_RO_Bit(ushort addr)
{
    Write_RO_bit(addr, 0, 1);
}

